package com.gitee.wsl.compose.modifier.draw

import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.scale
import androidx.compose.ui.unit.Dp


fun DrawScope.drawCrossHatch(
    color: Color,
    strokeWidth: Dp,
    spaceWidth: Dp,
) {
    drawHatch(color, strokeWidth, spaceWidth)
    // Draw again but flipped horizontally.
    scale(scaleX = -1f, scaleY = 1f) {
        drawHatch(color, strokeWidth, spaceWidth)
    }
}

private fun DrawScope.drawHatch(
    color: Color,
    strokeWidth: Dp,
    spaceWidth: Dp,
) {
    val strokeWidthPx = strokeWidth.toPx()
    val spaceWidthPx = spaceWidth.roundToPx()

    // Lower-left half.
    val ySegments = 0..size.height.toInt() step (spaceWidthPx + strokeWidthPx.toInt())
    ySegments.forEach { yStart ->
        drawLine(
            start = Offset(0f, yStart.toFloat()),
            // This will draw past the bounds in many cases, but it's simpler to just let clipping handle
            // that.
            end = Offset(size.height - yStart, size.height),
            color = color,
            strokeWidth = strokeWidthPx
        )
    }

    // Upper-right half.
    val xSegments = 0..size.width.toInt() step (spaceWidthPx + strokeWidthPx.toInt())
    xSegments.forEach { xStart ->
        drawLine(
            start = Offset(xStart.toFloat(), 0f),
            end = Offset(size.width, size.width - xStart),
            color = color,
            strokeWidth = strokeWidthPx
        )
    }
}